package com.tengju.bff.interfaces.shared.render;

import com.tengju.bff.interfaces.shared.Formatter;
import com.tengju.bff.interfaces.shared.KVVO;
import com.tengju.bff.interfaces.shared.RankDiffType;
import com.tengju.data.domain.model.analysis.Meta;
import com.tengju.data.domain.model.analysis.Row;
import com.tengju.data.domain.shared.CastUtil;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * @author chenhang
 * @Date 2021/7/12
 */
public class KVAssembler {

    public static List<KVVO> buildData(Collection<Meta> metas, Row row) {
        List<KVVO> result = new ArrayList<>();
        for (Meta meta : metas) {
            if (!meta.getIsShow()) {
                continue;
            }
            result.add(KVVO.of(meta.getShowName(), MetaUtil.getAmount(meta,row,metas)));
        }
        return result;
    }



    @Deprecated
    public static List<KVVO> buildData(Collection<Meta> metas, Row row, List<String> setTypeList) {
        List<KVVO> result = new ArrayList<>();
        for (Meta meta : metas) {
            if (!meta.getIsShow()) {
                continue;
            }
            String sqlColName = meta.getSqlColName();
            Object value = row.getValue(sqlColName);
            if (setTypeList.contains(sqlColName)) {
                double v = CastUtil.castDouble(value);
                int compare = Double.valueOf("0").compareTo(v);
                if (compare == 0) {
                    result.add(KVVO.of(meta.getShowName(), Formatter.formatter(meta, value)));
                } else if (compare > 0) {
                    result.add(KVVO.of(meta.getShowName(), Formatter.formatter(meta, value), RankDiffType.DOWN));
                } else {
                    result.add(KVVO.of(meta.getShowName(), Formatter.formatter(meta, value), RankDiffType.UP));
                }
            } else {
                result.add(KVVO.of(meta.getShowName(), Formatter.formatter(meta, value)));
            }
        }
        return result;
    }

    /**
     * 豆腐块的数据时按照行的形式存储
     * 展示的名称根据showName对应的数据展示
     * @param showMeta
     * @param metas
     * @param rows
     * @return
     */
    public static List<KVVO> buildData(Meta showMeta, Collection<Meta> metas, List<Row> rows) {
        if (showMeta == null || CollectionUtils.isEmpty(rows) || CollectionUtils.isEmpty(metas)) {
            return Collections.emptyList();
        }
        List<KVVO> result = new ArrayList<>();
        for (Row row : rows) {
            String showNameKey = showMeta.getShowName();
            result.add(KVVO.of(row.getValue(showNameKey), MetaUtil.getAmount(showMeta,row,metas)));
        }
        return result;
    }
}
